package ftpClitentPool.client;

import com.google.common.collect.Lists;
import ftpClitentPool.core.FtpClientPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2021-09-24 11:25
 **/
@Service
@Slf4j
public class FtpClientHelper {

    @Resource
    private FtpClientPool ftpClientPool;

    /**
     * 创建目录    单个不可递归
     * @param pathname 目录名称
     * @return
     * @throws Exception
     */
    public boolean makeDirectory(String pathname) throws Exception {

        FTPClient client = null;
        try {
            client = ftpClientPool.borrowObject();
            return client.makeDirectory(pathname);
        } catch (Exception e) {
            log.error("创建目录失败", e);
            throw e;
        } finally {
            ftpClientPool.returnObject(client);
        }
    }

    /**
     * 删除目录，单个不可递归
     * @param pathname
     * @return
     * @throws IOException
     */
	/*public boolean removeDirectory(String pathname) throws Exception {
		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			return client.removeDirectory(pathname);
		} catch (Exception e) {
			log.error("删除目录失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}*/

    /**
     * 删除文件 单个 ，不可递归
     * @param pathname
     * @return
     * @throws Exception
     */
	/*public boolean deleteFile(String pathname) throws Exception {

		FTPClient client = null;
		try {
			client = ftpClientPool.borrowObject();
			return client.deleteFile(pathname);
		} catch (Exception e) {
			log.error("创建文件失败", e);
			throw e;
		} finally {
			ftpClientPool.returnObject(client);
		}
	}*/

    /**
     * 上传文件
     * @param remote
     * @param local
     * @return
     * @throws Exception
     */
    public boolean storeFile(String remote, InputStream local) throws Exception {
        FTPClient client = null;
        try {
            client = ftpClientPool.borrowObject();
            //			client.enterLocalPassiveMode();
            if (remote.contains("/")) {
                // 创建服务器远程目录结构，创建失败直接返回
                createDirecroty(remote, client);
            }
            boolean res = client.storeFile(remote, local);
            client.changeWorkingDirectory("/");
            return res;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw e;
        } finally {
            ftpClientPool.returnObject(client);
        }
    }

    private int createDirecroty(String remote, FTPClient ftpClient) throws IOException {
        int status = 1;
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);

        if (!directory.equalsIgnoreCase("/")
                && !ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"), "iso-8859-1"))) {

            // 如果远程目录不存在，则递归创建远程服务器目录
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        return 0;
                    }
                }

                start = end + 1;
                end = directory.indexOf("/", start);

                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return status;
    }

    //先取两层吧
    public List<String> fileNames(String remote) {
        List<String> list = Lists.newArrayList();
        FTPClient client = null;
        try {
            client = ftpClientPool.borrowObject();
            client.changeWorkingDirectory(new String(remote.getBytes(), "iso-8859-1"));// 转移到FTP服务器目录
            FTPFile[] files = client.listFiles();
            if (files != null) {
                for (FTPFile ftpFile : files) {
                    String fileName = ftpFile.getName();
                    if (fileName.equals(".") || fileName.equals("..")) {
                        continue;
                    }
                    if (ftpFile.isFile()) {
                        list.add(fileName);
                    } else {
                        FTPFile[] files2 = client.listFiles(ftpFile.getName());
                        for (FTPFile ftpFile2 : files2) {
                            String fileName2 = ftpFile2.getName();
                            if (fileName2.equals(".") || fileName2.equals("..")) {
                                continue;
                            }
                            list.add(fileName + "/" + fileName2);
                        }
                    }
                }
            }
            client.changeWorkingDirectory("/");
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            ftpClientPool.returnObject(client);
        }
        return list;
    }

    public void remove(String pathName) {
        FTPClient client = null;
        try {
            client = ftpClientPool.borrowObject();
            //			client.changeWorkingDirectory(new String(path.getBytes(), "iso-8859-1"));// 转移到FTP服务器目录
            int code = client.dele(pathName);
        } catch (Exception e) {
            log.error("删除文件失败", e);
        } finally {
            ftpClientPool.returnObject(client);
        }
    }
}
